<template>
  <div id="users">
     <!-- 面包屑 -->
     <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <el-row :gutter="20">
          <el-col :span="7">
            <!-- 搜索与添加区域 -->
            <el-input placeholder="请输入内容" v-model="params.query" clearable  
              @keyup.enter.native="getUserList"
              class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click="getUserList" ></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addUser" icon="el-icon-plus">添加用户</el-button>
          </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userList" border stripe >
        <!-- 索引列 -->
        <el-table-column align="center" label="#" type="index"></el-table-column>
        <el-table-column align="center" label="姓名" prop="username"></el-table-column>
        <el-table-column align="center" label="邮箱" prop="email"></el-table-column>
        <el-table-column align="center" label="电话" prop="mobile"></el-table-column>
        <el-table-column align="center" label="角色" prop="role_name"></el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <el-switch
              @change="userStartChange(scope.row)"
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" >
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除 按钮 -->
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteUser(scope.row.id)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" :enterable="false" placement="top">
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <MyPage :params="params" :total="total" 
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
        ></MyPage>
    </el-card>
    <!-- 添加用户对话框 -->
    <Add @getUserList="getUserList" ref="AddRef"></Add>
    <!-- 编辑用户对话框 -->
    <Edit @getUserList = "getUserList" ref="EditRef" :EditFrom="EditFrom"></Edit>
    <!-- 分配角色的对话框 -->
    <setRole @getUserList="getUserList" ref="SetRoleRef" :userInfo="userInfo" :rolesList="rolesList"
      @clearUserInfo="()=>{return userInfo={}}"
    ></setRole>
  </div>
</template>
<script>
import MyPage from '@/components/Page.vue';
// import { showLoading } from '@/plugins/loading';
import Add from '@/views/User/Add.vue';
import Edit from '@/views/User/Edit.vue';
import setRole from '@/views/User/SetRole.vue';
export default {
    name: "MyUsers",
    components:{MyPage,Add,Edit,setRole},
    data() {
        return {
          search: "", // 搜索框
          // 获取用户列表的请求参数
          params: {
            query: "",  // 搜索关键字
            pagenum: 1,
            pagesize: 5   // 当前每页显示多少条
          }, 
          total: 0,
          // 点击被编辑的用户信息 
          EditFrom:{},
          // 点击被分配的用户列表
          userList: [],
          // 需要被分配父角色用户信息
          userInfo:{},
          // 所有角色的数据列表
          rolesList:[]
        };
    },
    watch:{
      "params.query"(value){
          if(value === "") this.getUserList();
      }
    },
    created() {
        this.getUserList();
    },
    methods: {
      // 展开添加用户框
      addUser(){
        this.$refs.AddRef.addDialogVisible = true;
      },  
       /**
       * @展示分配角色对话框
       */
       async setRole(userInfo){
        this.userInfo = userInfo;
        // 在展示对话框之前获取所有角色列表
        const {data:res} = await this.$http.get('roles');
        if (res.meta.status !== 200) {
          return this.$message.error('获取角色列表失败')
        }
        this.rolesList = res.data;
        this.$refs.SetRoleRef.setRelosDialogVisible = true;
      },  
      /**
       * @获取用户信息
       */
      async getUserList() {
          // showLoading()
          // 发起请求
          const {data:{meta:{status},data:{users,total}}} = await this.$http.get('/users',{
            params:{...this.params}
          });    
          if (status !== 200)
            return this.$message.error("获取用户列表失败");
            this.userList = users;
            this.total = total;
            // this.loading = false;
            // hideLoading();
      },
      /**
       * @name userStartChange
       * @监听状态开关修改
       */
      async userStartChange(value){
        console.log(value);
        const {data:res} = await this.$http.put(`users/${value.id}/state/${value.mg_state}`)
          console.log(res);
        if(res.meta.status !== 200){
          value.mg_status = !value.mg_status;
          return this.$message.error('更新用户状态失败');
        }
        this.$message.success(res.meta.msg)
      },
      /**
       * @展示用户编辑对话框
       */
       async showEditDialog(id){
        this.$refs.EditRef.aditDialogVisible = true;
        const {data:res} = await this.$http.get(`users/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        }
        this.EditFrom = {...res.data};
      },
      /**
       * @删除用户操作
       */
      async deleteUser(id){
       const confirm = await this.$confirm('是否永久删除该用户, 是否继续?', '提示', 
       {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(confirm !== "confirm"){
          return this.$message.info('已取消删除');
        }
        const {data:res} = await this.$http.delete(`users/${id}`);
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        }
          this.$message.success(res.meta.msg);
          this.getUserList();
      },
      /**
       * @name handleSizeChange{自定义事件}
       * @param {Number} value 接收最新显示条数
       * @子组件修改父组件
       */
      handleSizeChange(value){
        this.params.pagesize = value;
        this.getUserList();
      },
      /**
       * @name handleCurrentChange{自定义事件}
       * @param {Number} value 
       * @接收最新页码
       */
      handleCurrentChange(value){
        this.params.pagenum = value;
        this.getUserList();
      }
    },
}
</script>
<style lang="less" scoped>
</style>